package cn.tedu.egweibo3.controller;

import cn.tedu.egweibo3.mapper.UserMapper;
import cn.tedu.egweibo3.pojo.dto.UserDTO;
import cn.tedu.egweibo3.pojo.entity.User;
import cn.tedu.egweibo3.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/v1/users/")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @PostMapping("reg")
    public int selectByUser(@RequestBody UserDTO userDTO){
        System.out.println("userDTO = " + userDTO);
        UserVO userVO = userMapper.selectByUser(userDTO.getUsername());
        if (userVO != null){
            return 2;//被占用
        }
        User user = new User();
        BeanUtils.copyProperties(userDTO,user);
        user.setCreated(new Date());
        userMapper.insert(user);
        return 1;//注册成功
    }

    @PostMapping("login")
    public int login(@RequestBody UserDTO userDTO,HttpSession session){
        System.out.println("userDTO = " + userDTO + ", session = " + session);
        UserVO userVO = userMapper.selectByUser(userDTO.getUsername());
        if(userVO==null){
            return 3;//用户名错误
        }
        if (userDTO.getPassword().equals(userVO.getPassword())){
            session.setAttribute("user",userVO);
            return 1;//登录成功
        }
        return 2;//密码错误
    }

    @GetMapping("currentUser")
    public UserVO currentUser(HttpSession session){
        UserVO userVO = (UserVO) session.getAttribute("user");
        return userVO;
    }

    @GetMapping("logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }
}
